<?php
// admin/edit_product.php - Edit Product
// Student: [Your Name], ID: [Your Student ID]

session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Load products data
$jsonFile = '../data/products.json';
$productsData = file_get_contents($jsonFile);
$products = json_decode($productsData, true);

// Get product ID from URL
$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Find the product to edit
$productToEdit = null;
foreach ($products as $index => $product) {
    if ($product['id'] === $productId) {
        $productToEdit = $product;
        $productIndex = $index;
        break;
    }
}

// If product not found, redirect to dashboard
if (!$productToEdit) {
    header('Location: index.php?message=Product not found');
    exit;
}

$error = '';
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $requiredFields = ['name', 'price', 'category', 'quantity', 'supplier', 'origin_country', 'spice_level'];
    $missingFields = [];
    
    foreach ($requiredFields as $field) {
        if (empty(trim($_POST[$field] ?? ''))) {
            $missingFields[] = $field;
        }
    }
    
    if (!empty($missingFields)) {
        $error = "Please fill in all required fields: " . implode(', ', $missingFields);
    } else {
        // Update product data
        $updatedProduct = [
            'id' => $productId,
            'name' => trim($_POST['name']),
            'image_url' => !empty(trim($_POST['image_url'])) ? trim($_POST['image_url']) : 'images/placeholder.jpg',
            'price' => floatval($_POST['price']),
            'description' => trim($_POST['description']),
            'supplier' => trim($_POST['supplier']),
            'category' => trim($_POST['category']),
            'discount' => intval($_POST['discount']),
            'quantity' => intval($_POST['quantity']),
            'origin_country' => trim($_POST['origin_country']),
            'spice_level' => trim($_POST['spice_level'])
        ];
        
        // Validate numeric fields
        if ($updatedProduct['price'] <= 0) {
            $error = "Price must be greater than 0";
        } elseif ($updatedProduct['quantity'] < 0) {
            $error = "Quantity cannot be negative";
        } elseif ($updatedProduct['discount'] < 0 || $updatedProduct['discount'] > 100) {
            $error = "Discount must be between 0 and 100";
        } else {
            // Update product in array
            $products[$productIndex] = $updatedProduct;
            
            // Save back to JSON file
            if (file_put_contents($jsonFile, json_encode($products, JSON_PRETTY_PRINT))) {
                $success = "Product updated successfully!";
                $productToEdit = $updatedProduct; // Update displayed data
            } else {
                $error = "Error saving product data! Please check file permissions.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product - Admin Panel</title>
    <link rel="stylesheet" href="../css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <header class="wp-header">
        <div class="header-container">
            <div class="site-branding">
                <h1 class="site-title">Edit Product</h1>
                <p class="site-description">Global Food Market - Admin</p>
            </div>
            <nav class="main-navigation">
                <ul>
                    <li><a href="../products.php">View Store</a></li>
                    <li><a href="index.php">Dashboard</a></li>
                    <li><a href="logout.php">Logout</a></li>
                </ul>
            </nav>
        </div>
    </header>
    
    <div class="admin-container">
        <div class="page-actions">
            <a href="index.php" class="btn btn-secondary">← Back to Dashboard</a>
        </div>
        
        <div class="form-container">
            <h2>Edit Product: <?php echo htmlspecialchars($productToEdit['name']); ?></h2>
            
            <?php if (!empty($error)): ?>
                <div class="error-message"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if (!empty($success)): ?>
                <div class="success-message"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>
            
            <form method="POST" class="product-form">
                <div class="form-section">
                    <h3>Basic Information</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="name">Product Name *</label>
                            <input type="text" id="name" name="name" 
                                   value="<?php echo htmlspecialchars($productToEdit['name']); ?>" 
                                   required>
                        </div>
                        
                        <div class="form-group">
                            <label for="category">Category *</label>
                            <select id="category" name="category" required>
                                <option value="">Select Category</option>
                                <option value="Sauces" <?php echo $productToEdit['category'] === 'Sauces' ? 'selected' : ''; ?>>Sauces</option>
                                <option value="Snacks" <?php echo $productToEdit['category'] === 'Snacks' ? 'selected' : ''; ?>>Snacks</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea id="description" name="description" rows="3"><?php echo htmlspecialchars($productToEdit['description']); ?></textarea>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3>Pricing & Inventory</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="price">Price ($) *</label>
                            <input type="number" id="price" name="price" step="0.01" min="0" 
                                   value="<?php echo htmlspecialchars($productToEdit['price']); ?>" 
                                   required>
                        </div>
                        
                        <div class="form-group">
                            <label for="discount">Discount (%)</label>
                            <input type="number" id="discount" name="discount" min="0" max="100" 
                                   value="<?php echo htmlspecialchars($productToEdit['discount']); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="quantity">Quantity in Stock *</label>
                            <input type="number" id="quantity" name="quantity" min="0" 
                                   value="<?php echo htmlspecialchars($productToEdit['quantity']); ?>" 
                                   required>
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3>Supplier & Origin</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="supplier">Supplier *</label>
                            <input type="text" id="supplier" name="supplier" 
                                   value="<?php echo htmlspecialchars($productToEdit['supplier']); ?>" 
                                   required>
                        </div>
                        
                        <div class="form-group">
                            <label for="origin_country">Origin Country *</label>
                            <input type="text" id="origin_country" name="origin_country" 
                                   value="<?php echo htmlspecialchars($productToEdit['origin_country']); ?>" 
                                   required>
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <h3>Additional Details</h3>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="image_url">Image URL</label>
                            <input type="url" id="image_url" name="image_url" 
                                   value="<?php echo htmlspecialchars($productToEdit['image_url']); ?>">
                            <small>Leave empty to use placeholder image</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="spice_level">Spice Level *</label>
                            <select id="spice_level" name="spice_level" required>
                                <option value="">Select Level</option>
                                <option value="Not Spicy" <?php echo $productToEdit['spice_level'] === 'Not Spicy' ? 'selected' : ''; ?>>Not Spicy</option>
                                <option value="Mild" <?php echo $productToEdit['spice_level'] === 'Mild' ? 'selected' : ''; ?>>Mild</option>
                                <option value="Medium" <?php echo $productToEdit['spice_level'] === 'Medium' ? 'selected' : ''; ?>>Medium</option>
                                <option value="Hot" <?php echo $productToEdit['spice_level'] === 'Hot' ? 'selected' : ''; ?>>Hot</option>
                                <option value="Very Hot" <?php echo $productToEdit['spice_level'] === 'Very Hot' ? 'selected' : ''; ?>>Very Hot</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        Update Product
                    </button>
                    <a href="index.php" class="btn btn-cancel">Cancel</a>
                </div>
            </form>
        </div>
    </div>
    
    <footer class="wp-footer">
        <div class="footer-container">
            <div class="footer-bottom">
                <p>&copy; 2024 Global Food Market - Admin Panel</p>
            </div>
        </div>
    </footer>
</body>
</html>